﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using NextCMS.Models;
using System.Web;

namespace NextCMS.DataAccess.XMLDataAccess
{
    internal class Modules : IModules
    {
        private string FilePath = HttpContext.Current.Server.MapPath("~") + "/App_Data/Modules.xml";
        private string Descendants = "Module";
        XDocument doc = null;
        public Modules()
        {
            doc = XDocument.Load(FilePath);  //load the xml file.
        }
        public Models.ModuleModel GetById(int id)
        {
            var q = from d in doc.Descendants(Descendants)
                    where (int)d.Element("Id") == id
                    select new ModuleModel
                    {
                        Id = (int)d.Element("Id"),
                        Code = d.Element("Code").Value,
                        Name = d.Element("Name").Value,
                        Type = d.Element("Type") != null ? d.Element("Type").Value : "",
                        Settings = d.Element("Settings") != null ? d.Element("Settings").Value : "",
                        SubModules = (from s in d.Elements("SubModules").Elements("SubModule")
                                      select new SubModule
                                      {
                                          Id = (int)d.Element("Id"),
                                          Code = s.Element("Code").Value,
                                          Name = s.Element("Name").Value,
                                          Type = s.Element("Type") != null ? s.Element("Type").Value : "",
                                          Settings = s.Element("Settings") != null ? s.Element("Settings").Value : "",
                                      }).ToList()
                    };
            return q.FirstOrDefault();
        }
        public IEnumerable<ModuleModel> GetAllModules()
        {
            var q = from d in doc.Descendants(Descendants)
                    select new ModuleModel
                    {
                        Id = (int)d.Element("Id"),
                        Code = d.Element("Code").Value,
                        Name = d.Element("Name").Value
                    };
            return q;
        }

        public void Dispose()
        {
            doc = null;
        }
    }
}
